import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:go_router/go_router.dart';
import 'package:material_dialogs/dialogs.dart';
import 'package:material_dialogs/shared/types.dart';
import 'package:material_dialogs/widgets/buttons/icon_button.dart';
import 'package:material_dialogs/widgets/buttons/icon_outline_button.dart';
import 'package:tracker/pages/home/location/model/monitor_data_resp.dart';
import 'package:tracker/theme/app_theme.dart';
import 'package:tracker/utils/device_utils.dart';

import '../common/widget/common.dart';

class ToastUtils {
  // 程序启动时调用
  static void init() {
    // loading 配置
    EasyLoading.init();
    EasyLoading.instance.indicatorType = EasyLoadingIndicatorType.threeBounce;
  }

  static void showSuccess(String message) {
    EasyLoading.showSuccess(message);
  }

  static void showToast(String message) {
    EasyLoading.showToast(message);
  }

  static void showLoading(
      {String status = '加载中...',
      bool dismissOnTap = false,
      EasyLoadingMaskType maskType = EasyLoadingMaskType.none}) {
    EasyLoading.show(
        status: status, dismissOnTap: dismissOnTap, maskType: maskType);
  }

  static void dismissLoading() {
    EasyLoading.dismiss();
  }

  /// 通用弹窗
  static void showSimpleDialog(BuildContext context,
      {String title = '',
      String content = '',
      String confirmTitle = '确定',
      String cancelTitle = '取消',
      Function? confirmCallback,
      Function? cancelCallback,
      bool showCancel = false}) {
    showDialog(
        context: context,
        barrierDismissible: false, // 设置为false，点击外部不会关闭对话框
        builder: (ctx) {
          return AlertDialog(
            title: Text(title),
            content: Text(content),
            backgroundColor: Colors.white,
            surfaceTintColor: Colors.white,
            actions: [
              if (showCancel)
                TextButton(
                  onPressed: () {
                    Navigator.of(ctx).pop();
                    cancelCallback?.call();
                  },
                  child: Text(cancelTitle,
                      style: TextStyle(color: Colors.grey[600])),
                ),
              TextButton(
                onPressed: () {
                  Navigator.of(ctx).pop();
                  confirmCallback?.call();
                },
                child: Text(confirmTitle),
              ),
            ],
          );
        });
  }

  static void showSimpleBottomDialog(BuildContext context,
      {String title = '',
      String content = '',
      String confirmTitle = '',
      String cancelTitle = '',
      Function? confirmCallback,
      Function? cancelCallback}) {
    var actions = <Widget>[];
    if (cancelTitle.isNotEmpty) {
      actions.add(TextButton(
        onPressed: () {
          context.pop();
          cancelCallback?.call();
        },
        style: ButtonStyle(
          backgroundColor: MaterialStateProperty.all(Colors.grey[200]),
          foregroundColor: MaterialStateProperty.all(Colors.grey[800]),
        ),
        child: Text(cancelTitle),
      ));
    }
    if (confirmTitle.isNotEmpty) {
      actions.add(TextButton(
        onPressed: () {
          context.pop();
          confirmCallback?.call();
        },
        // 背景色
        style: ButtonStyle(
          backgroundColor:
              MaterialStateProperty.all(AppTheme.themeConfig.primaryColor),
          foregroundColor: MaterialStateProperty.all(Colors.white),
        ),
        child: Text(confirmTitle),
      ));
    }
    Dialogs.bottomMaterialDialog(
      context: context,
      isScrollControlled: true,
      title: title,
      msg: content,
      actions: actions,
    );
  }

  /// 购买增值服务弹窗
  static void showBuyVip(BuildContext context, void Function()? confirmCallback,
      {void Function()? cancelCallback}) {
    Dialogs.materialDialog(
      context: context,
      color: Colors.white,
      title: '温馨提示',
      // 点击空白处，不关闭
      barrierDismissible: false,
      customView: Column(
        children: [
          Container(
              margin: const EdgeInsets.only(top: 12, left: 20, right: 20),
              alignment: Alignment.centerLeft,
              child: Text(
                '您的设备待激活。\n激活后您将获得最佳服务:',
                style: TextStyle(
                  color: AppTheme.themeConfig.primaryTextColor,
                  fontSize: 16,
                  fontWeight: FontWeight.bold,
                ),
              )),
          Container(
            margin: const EdgeInsets.only(top: 12, left: 20, right: 20),
            alignment: Alignment.centerLeft,
            child: Text(
              '1.配送的SIM卡激活、0月租、免费使用。\n' +
                  '2.获得1年至终身的定位流量。\n' +
                  '3.套餐时限内免费实时定位。\n' +
                  '4.套餐时限内云端历史轨迹储存。\n' +
                  '5.免费使用异响防盗服务。\n' +
                  '6.异响报警循环储存100天。\n' +
                  '7.赠送增值服务短信预警10条。\n' +
                  '8.赠送电话预警5次。\n' +
                  '9.7x10h远程技术支持服务。\n' +
                  '10.体验更多APP创新服务。\n',
              style: TextStyle(
                color: AppTheme.themeConfig.secondaryTextColor,
                fontSize: 14,
              ),
            ),
          ),
        ],
      ),
      customViewPosition: CustomViewPosition.BEFORE_MESSAGE,
      actions: [
        IconsOutlineButton(
          onPressed: () {
            context.pop();
            cancelCallback?.call();
          },
          text: '退出',
          iconData: Icons.cancel_outlined,
          textStyle: TextStyle(color: AppTheme.themeConfig.primaryTextColor),
          iconColor: AppTheme.themeConfig.primaryTextColor,
          color: Colors.white,
        ),
        IconsButton(
          onPressed: () {
            context.pop();
            confirmCallback?.call();
          },
          text: '去购买',
          iconData: Icons.check_circle_outline,
          color: AppTheme.themeConfig.primaryColor,
          textStyle: const TextStyle(color: Colors.white),
          iconColor: Colors.white,
        ),
      ],
    );
  }

  /// 增值服务广告弹窗
  static void showValueAddedServiceAd(
      BuildContext context, void Function()? confirmCallback,
      {void Function()? cancelCallback}) {
    Dialogs.materialDialog(
      context: context,
      color: Colors.white,
      title: '发现紧急情况',
      // 点击空白处，不关闭
      barrierDismissible: false,
      customView: Column(
        children: [
          Container(
            margin: const EdgeInsets.only(top: 12, left: 20, right: 20),
            alignment: Alignment.center,
            child: Text(
              '请立即开启秒定模式+轨迹存储\n' +
                  '将为您提供以下服务\n' +
                  '1、高效率定位频次\n' +
                  '2、高准度轨迹回放\n' +
                  '3、降低设备离线率\n' +
                  '4、提升告警送达率\n' +
                  '5、数据访问与安全\n' +
                  '6、减少数据泄露的风险\n' +
                  '7、轨迹存储长达180天\n' +
                  '8、轨迹云存储、查询、回放\n' +
                  '9、24小时远程技术维护\n',
              style: TextStyle(
                color: AppTheme.themeConfig.secondaryTextColor,
                fontSize: 14,
              ),
            ),
          ),
        ],
      ),
      customViewPosition: CustomViewPosition.BEFORE_MESSAGE,
      actions: [
        IconsOutlineButton(
          onPressed: () {
            context.pop();
            cancelCallback?.call();
          },
          text: '以后再说',
          iconData: Icons.cancel_outlined,
          textStyle: TextStyle(color: AppTheme.themeConfig.primaryTextColor),
          iconColor: AppTheme.themeConfig.primaryTextColor,
          color: Colors.white,
        ),
        IconsButton(
          onPressed: () {
            context.pop();
            confirmCallback?.call();
          },
          text: '查看详情',
          iconData: Icons.check_circle_outline,
          color: AppTheme.themeConfig.primaryColor,
          textStyle: const TextStyle(color: Colors.white),
          iconColor: Colors.white,
        ),
      ],
    );
  }

  /// 自检结果弹窗
  static void showSelfTestResultDialog(BuildContext context,
      {String title = '',
      String content = '',
      String confirmTitle = '确定',
      String cancelTitle = '取消',
      Function? confirmCallback,
      Function? cancelCallback,
      MonitorData? monitorData}) {
    showDialog(
        context: context,
        builder: (_context) {
          return AlertDialog(
            title: const Text('自检结果'),
            content: Container(
              child: Column(
                // 最小高度
                mainAxisSize: MainAxisSize.min,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                      '在线状态：${DeviceUtils.getStatusText(monitorData?.deviceStatus)}'),
                  Text('充电状态：${monitorData?.chargingStatusName ?? ''}'),
                  Text('电量：${monitorData?.batteryPercentage ?? ''}%'),
                  Text('定位模式：${monitorData?.workModeName ?? ''}'),
                  Text('信号强度：${monitorData?.csq ?? ''}'),
                  Text('定位优先级：${monitorData?.locationPriority ?? ''}'),
                  Text('ICCID：${monitorData?.iccid ?? ''}'),
                  if (monitorData?.address != null)
                    Text('详细地址：${monitorData?.address ?? ''}'),
                  Text('更新时间：${monitorData?.lastCommunicationTime ?? ''}'),
                ],
              ),
            ),
            backgroundColor: Colors.white,
            surfaceTintColor: Colors.white,
            actions: [
              TextButton(
                onPressed: () {
                  Navigator.of(_context).pop();
                  confirmCallback?.call();
                },
                child: const Text('好的'),
              ),
            ],
          );
        });
  }

  /// 设备号登录时，弹窗提示
  static void showDeviceLoginDialog(BuildContext context) {
    showDialog(
        context: context,
        builder: (ctx) {
          return AlertDialog(
            title: Text('温馨提示',
                style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
            content: const Text(
                '绑定多台设备请使用手机号登录\n' +
                    '退出登录-登录页选择"手机号登录"\n' +
                    '输入您的手机号，默认密码123456',
                style: TextStyle(fontSize: 15)),
            backgroundColor: Colors.white,
            surfaceTintColor: Colors.white,
            actions: [
              TextButton(
                onPressed: () {
                  Navigator.of(ctx).pop();
                },
                child: const Text('好的'),
              ),
            ],
          );
        });
  }

  static void showDeleteDialog(
    BuildContext context, {
    VoidCallback? confirmCallback,
  }) {
    showDialog(
        context: context,
        builder: (ctx) {
          return AlertDialog(
            shape:
                RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
            title: const Center(
              child: Text('温馨提示', style: TextStyle(fontSize: 16)),
            ),
            content: Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                const Text(
                  '请确定要删除已选的安防录音，\n该操作不可恢复',
                  style: TextStyle(fontSize: 16),
                  textAlign: TextAlign.center,
                ),
                GestureDetector(
                  onTap: () {
                    Navigator.of(context).pop();
                    if (confirmCallback != null) {
                      confirmCallback();
                    }
                  },
                  child: Container(
                    margin: const EdgeInsets.only(top: 10),
                    padding: const EdgeInsets.symmetric(vertical: 10),
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(30),
                      color: AppTheme.themeConfig.primaryColor,
                    ),
                    child: lpText("确认", size: 16, color: Colors.white),
                  ),
                ),
                GestureDetector(
                  onTap: () {
                    Navigator.of(context).pop();
                  },
                  child: Container(
                    margin: const EdgeInsets.only(top: 10),
                    padding: const EdgeInsets.symmetric(vertical: 10),
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(30),
                      color: const Color(0xff9D9D9E),
                    ),
                    child: lpText("返回", size: 16, color: Colors.white),
                  ),
                )
              ],
            ),
            backgroundColor: Colors.white,
            surfaceTintColor: Colors.white,
          );
        });
  }

  static void showCheckDateDialog(
      BuildContext context, {
        required String content,
        VoidCallback? confirmCallback,
      }) {
    showDialog(
        context: context,
        builder: (ctx) {
          return AlertDialog(
            shape:
            RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
            title: const Center(
              child: Text('温馨提示', style: TextStyle(fontSize: 16)),
            ),
            content: Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Text(
                  content,
                  style: TextStyle(fontSize: 16),
                  textAlign: TextAlign.center,
                ),
                GestureDetector(
                  onTap: () {
                    Navigator.of(context).pop();
                    if (confirmCallback != null) {
                      confirmCallback();
                    }
                  },
                  child: Container(
                    margin: const EdgeInsets.only(top: 10),
                    padding: const EdgeInsets.symmetric(vertical: 10),
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(30),
                      color: AppTheme.themeConfig.primaryColor,
                    ),
                    child: lpText("好的", size: 16, color: Colors.white),
                  ),
                )
              ],
            ),
            backgroundColor: Colors.white,
            surfaceTintColor: Colors.white,
          );
        });
  }
}
